const modelService = require('../services/modelService');
const path = require('path');
const fs = require('fs-extra');
const fileUtils = require('../utils/fileUtils');

/**
 * 获取模型列表
 */
exports.getModels = async (req, res) => {
    try {
        const { success, data, error } = await modelService.getAllModels(req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        return res.json({
            status: 200,
            data
        });
    } catch (error) {
        console.error('获取模型列表错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建新模型
 */
exports.createModel = async (req, res) => {
    try {
        const {
            name,
            description,
            geometry,
            material,
            customGeometry,
            booleanOperation,
            additionalObjects,
            exportSettings,
            sharing
        } = req.body;

        // 验证必填字段
        if (!name) {
            return res.status(400).json({
                status: 400,
                message: '模型名称不能为空'
            });
        }

        // 准备模型数据
        const modelData = {
            name,
            description,
            exportSettings,
            sharing
        };

        // 如果提供了额外几何体，添加到模型数据中
        if (additionalObjects && Array.isArray(additionalObjects)) {
            modelData.additionalObjects = additionalObjects;
        }

        // 如果提供了几何体数据，添加到模型数据中
        if (geometry) {
            // 处理特殊几何体
            if (geometry.type === 'custom' && customGeometry) {
                modelData.geometry = {
                    ...geometry,
                    customGeometry
                };
            } else if (geometry.type === 'group' && geometry.children && Array.isArray(geometry.children)) {
                modelData.geometry = {
                    ...geometry
                };
            } else if (geometry.type === 'text3d' && geometry.dimensions && geometry.dimensions.text) {
                modelData.geometry = {
                    ...geometry
                };
            } else if (['lathe', 'extrude', 'tube'].includes(geometry.type) &&
                geometry.dimensions &&
                geometry.dimensions.points &&
                Array.isArray(geometry.dimensions.points)) {
                modelData.geometry = {
                    ...geometry
                };
            } else if (geometry.type === 'external_model') {
                // 处理外部导入的模型类型
                modelData.geometry = {
                    ...geometry
                };
            } else {
                modelData.geometry = {
                    ...geometry
                };
            }

            // 添加材质信息
            if (material) {
                modelData.geometry.material = material;
            }

            // 添加布尔运算信息
            if (booleanOperation && booleanOperation.type && booleanOperation.targetId) {
                modelData.geometry.booleanOperation = booleanOperation;
            }
        }

        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        // 为几何体模型生成缩略图
        if (geometry && data.model && data.model.id) {
            try {
                // 确保存储目录存在
                const storagePath = await fileUtils.ensureStorageDir(req.userId, data.model.id);
                const thumbnailPath = path.join(storagePath, `geometry_thumbnail.png`);

                // 生成缩略图
                const base64Thumbnail = await fileUtils.generateGeometryThumbnail(geometry, thumbnailPath);

                // 更新模型缩略图信息
                await modelService.updateModel(data.model.id, req.userId, {
                    thumbnail: {
                        path: thumbnailPath,
                        base64: base64Thumbnail,
                        generateDate: new Date()
                    }
                });
            } catch (thumbnailError) {
                console.error('生成几何体缩略图错误:', thumbnailError);
                // 缩略图生成失败不影响模型创建结果
            }
        }

        return res.status(201).json({
            status: 201,
            data
        });
    } catch (error) {
        console.error('创建模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 更新模型信息
 */
exports.updateModel = async (req, res) => {
    try {
        const { modelId } = req.params;
        const {
            name,
            description,
            geometry,
            material,
            customGeometry,
            booleanOperation,
            additionalObjects,  // 添加对额外几何体的支持
            exportSettings,
            sharing
        } = req.body;

        // 确保至少有一个字段需要更新
        if (!name && !description && !geometry && !material && !customGeometry && !booleanOperation && !additionalObjects && !exportSettings && !sharing) {
            return res.status(400).json({
                status: 400,
                message: '请提供需要更新的字段'
            });
        }

        const updateData = {};
        if (name) updateData.name = name;
        if (description) updateData.description = description;
        if (exportSettings) updateData.exportSettings = exportSettings;
        if (sharing) updateData.sharing = sharing;

        // 处理额外几何体数组的更新
        if (additionalObjects) {
            if (Array.isArray(additionalObjects)) {
                updateData.additionalObjects = additionalObjects;
            } else {
                return res.status(400).json({
                    status: 400,
                    message: 'additionalObjects必须是数组'
                });
            }
        }

        // 处理几何体和相关数据的更新
        if (geometry || material || customGeometry || booleanOperation) {
            // 先获取当前模型信息
            const { success: getSuccess, data: currentModel } = await modelService.getModelById(modelId, req.userId);

            if (!getSuccess || !currentModel) {
                return res.status(404).json({
                    status: 404,
                    message: '找不到模型'
                });
            }

            // 如果没有提供完整的几何体数据，则使用现有数据
            const currentGeometry = currentModel.geometry || {};

            if (geometry) {
                // 处理特殊几何体类型
                if (geometry.type === 'custom' && customGeometry) {
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry,
                        customGeometry
                    };
                } else if (geometry.type === 'group' && geometry.children && Array.isArray(geometry.children)) {
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry
                    };
                } else if (geometry.type === 'text3d' && geometry.dimensions && geometry.dimensions.text) {
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry
                    };
                } else if (['lathe', 'extrude', 'tube'].includes(geometry.type) &&
                    geometry.dimensions &&
                    geometry.dimensions.points &&
                    Array.isArray(geometry.dimensions.points)) {
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry
                    };
                } else if (geometry.type === 'external_model') {
                    // 处理外部导入的模型类型
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry
                    };
                } else {
                    updateData.geometry = {
                        ...currentGeometry,
                        ...geometry
                    };
                }
            } else if (currentGeometry) {
                // 如果没有提供几何体但有其他变更需要应用到现有几何体
                updateData.geometry = { ...currentGeometry };
            }

            // 更新材质信息
            if (material && updateData.geometry) {
                updateData.geometry.material = {
                    ...(updateData.geometry.material || {}),
                    ...material
                };
            }

            // 更新布尔运算信息
            if (booleanOperation && booleanOperation.type && booleanOperation.targetId) {
                if (updateData.geometry) {
                    updateData.geometry.booleanOperation = booleanOperation;
                } else if (currentGeometry) {
                    updateData.geometry = {
                        ...currentGeometry,
                        booleanOperation
                    };
                }
            }

            // 只更新自定义几何体
            if (!geometry && customGeometry && currentGeometry) {
                updateData.geometry = {
                    ...currentGeometry,
                    customGeometry
                };
            }
        }

        const { success, message, error } = await modelService.updateModel(modelId, req.userId, updateData);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        // 如果更新了几何体，重新生成缩略图
        if (updateData.geometry) {
            try {
                // 确保存储目录存在
                const storagePath = await fileUtils.ensureStorageDir(req.userId, modelId);
                const thumbnailPath = path.join(storagePath, `geometry_thumbnail.png`);

                // 生成缩略图
                const base64Thumbnail = await fileUtils.generateGeometryThumbnail(updateData.geometry, thumbnailPath);

                // 更新模型缩略图信息
                await modelService.updateModel(modelId, req.userId, {
                    thumbnail: {
                        path: thumbnailPath,
                        base64: base64Thumbnail,
                        generateDate: new Date()
                    }
                });
            } catch (thumbnailError) {
                console.error('更新几何体缩略图错误:', thumbnailError);
                // 缩略图更新失败不影响模型更新结果
            }
        }

        return res.json({
            status: 200,
            message
        });
    } catch (error) {
        console.error('更新模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 删除模型
 */
exports.deleteModel = async (req, res) => {
    try {
        const { modelId } = req.params;

        const { success, message, error } = await modelService.deleteModel(modelId, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        return res.json({
            status: 200,
            message
        });
    } catch (error) {
        console.error('删除模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 获取可用几何体类型
 */
exports.getGeometryTypes = async (req, res) => {
    try {
        const geometryTypes = [
            {
                type: 'cube',
                name: '立方体',
                properties: ['width', 'height', 'depth', 'color', 'material']
            },
            {
                type: 'sphere',
                name: '球体',
                properties: ['radius', 'segments', 'color', 'material']
            },
            {
                type: 'cylinder',
                name: '圆柱体',
                properties: ['radius', 'height', 'segments', 'color', 'material']
            },
            {
                type: 'cone',
                name: '圆锥体',
                properties: ['radius', 'height', 'segments', 'color', 'material']
            },
            {
                type: 'torus',
                name: '圆环',
                properties: ['radius', 'tube', 'segments', 'color', 'material']
            },
            {
                type: 'plane',
                name: '平面',
                properties: ['width', 'height', 'color', 'material']
            },
            {
                type: 'text3d',
                name: '3D文本',
                properties: ['text', 'font', 'height', 'depth', 'color', 'material']
            },
            {
                type: 'lathe',
                name: '车削体',
                properties: ['points', 'segments', 'color', 'material']
            },
            {
                type: 'extrude',
                name: '挤出体',
                properties: ['points', 'depth', 'bevelEnabled', 'bevelThickness', 'bevelSize', 'bevelSegments', 'color', 'material']
            },
            {
                type: 'tube',
                name: '管状体',
                properties: ['points', 'radius', 'segments', 'color', 'material']
            },
            {
                type: 'custom',
                name: '自定义几何体',
                properties: ['vertices', 'faces', 'color', 'material']
            },
            {
                type: 'group',
                name: '组合体',
                properties: ['children']
            },
            {
                type: 'external_model',
                name: '外部导入模型',
                properties: ['file', 'color', 'material', 'position', 'rotation', 'scale']
            }
        ];

        const materialTypes = [
            { type: 'basic', name: '基础材质' },
            { type: 'standard', name: '标准材质' },
            { type: 'phong', name: 'Phong材质' },
            { type: 'lambert', name: 'Lambert材质' },
            { type: 'normal', name: '法线材质' },
            { type: 'physical', name: '物理材质' }
        ];

        const materialProperties = [
            { name: 'wireframe', type: 'boolean' },
            { name: 'metalness', type: 'number', range: [0, 1] },
            { name: 'roughness', type: 'number', range: [0, 1] },
            { name: 'opacity', type: 'number', range: [0, 1] },
            { name: 'transparent', type: 'boolean' },
            { name: 'texture', type: 'file', formats: ['jpg', 'png'] }
        ];

        const booleanOperations = [
            { type: 'union', name: '合并' },
            { type: 'subtract', name: '减去' },
            { type: 'intersect', name: '交集' }
        ];

        const exportFormats = [
            { type: 'stl', name: 'STL格式', description: '适用于3D打印' },
            { type: 'obj', name: 'OBJ格式', description: '通用3D模型格式' },
            { type: 'gltf', name: 'GLTF格式', description: '支持材质和动画' },
            { type: 'glb', name: 'GLB格式', description: 'GLTF的二进制版本' }
        ];

        return res.json({
            status: 200,
            data: {
                geometryTypes,
                materialTypes,
                materialProperties,
                booleanOperations,
                exportFormats
            }
        });
    } catch (error) {
        console.error('获取几何体类型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 获取模型详情
 */
exports.getModelById = async (req, res) => {
    try {
        const { modelId } = req.params;

        const { success, data, error } = await modelService.getModelById(modelId, req.userId);

        if (!success) {
            return res.status(404).json({
                status: 404,
                message: error
            });
        }

        // 确保返回完整的模型信息，包括额外几何体
        const responseData = {
            ...data,
            id: data._id.toString(),
            additionalObjects: data.additionalObjects || []
        };

        return res.json({
            status: 200,
            data: responseData
        });
    } catch (error) {
        console.error('获取模型详情错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 执行布尔运算
 */
exports.performBooleanOperation = async (req, res) => {
    try {
        const { modelId } = req.params;
        const { targetModelId, operationType, newModelName } = req.body;

        if (!targetModelId || !operationType || !newModelName) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：目标模型ID、运算类型或新模型名称'
            });
        }

        // 验证运算类型
        if (!['union', 'subtract', 'intersect'].includes(operationType)) {
            return res.status(400).json({
                status: 400,
                message: '不支持的布尔运算类型，支持的类型有：union, subtract, intersect'
            });
        }

        // 获取源模型
        const { success: sourceSuccess, data: sourceModel, error: sourceError } =
            await modelService.getModelById(modelId, req.userId);

        if (!sourceSuccess) {
            return res.status(404).json({
                status: 404,
                message: sourceError || '源模型不存在或无权限访问'
            });
        }

        // 获取目标模型
        const { success: targetSuccess, data: targetModel, error: targetError } =
            await modelService.getModelById(targetModelId, req.userId);

        if (!targetSuccess) {
            return res.status(404).json({
                status: 404,
                message: targetError || '目标模型不存在或无权限访问'
            });
        }

        // 创建新模型数据
        const newModelData = {
            name: newModelName,
            description: `通过布尔运算(${operationType})创建，源模型：${sourceModel.name}，目标模型：${targetModel.name}`,
            geometry: {
                type: 'group',  // 布尔运算结果存储为组合类型
                booleanOperation: {
                    type: operationType,
                    sourceId: modelId,
                    targetId: targetModelId
                }
            }
        };

        // 创建新模型
        const { success, data, error } = await modelService.createModel(newModelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '布尔运算失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: `布尔运算(${operationType})成功，已创建新模型`
        });
    } catch (error) {
        console.error('布尔运算错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建自定义几何体模型
 */
exports.createCustomModel = async (req, res) => {
    try {
        const { name, description, vertices, faces, normals, material } = req.body;

        if (!name || !vertices || !faces) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：模型名称、顶点数组或面数组'
            });
        }

        // 验证顶点和面数据
        if (!Array.isArray(vertices) || vertices.length === 0) {
            return res.status(400).json({
                status: 400,
                message: '顶点数据必须是非空数组'
            });
        }

        if (!Array.isArray(faces) || faces.length === 0) {
            return res.status(400).json({
                status: 400,
                message: '面数据必须是非空数组'
            });
        }

        // 创建模型数据
        const modelData = {
            name,
            description: description || `自定义模型(${vertices.length}个顶点, ${faces.length}个面)`,
            geometry: {
                type: 'custom',
                customGeometry: {
                    vertices,
                    faces,
                    normals: normals || []
                }
            }
        };

        // 添加材质信息
        if (material) {
            modelData.geometry.material = material;
        }

        // 创建模型
        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '创建自定义模型失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: '自定义模型创建成功'
        });
    } catch (error) {
        console.error('创建自定义模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建3D文本模型
 */
exports.createText3DModel = async (req, res) => {
    try {
        const { name, description, text, font, height, depth, material } = req.body;

        if (!name || !text) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：模型名称或文本内容'
            });
        }

        // 创建模型数据
        const modelData = {
            name,
            description: description || `3D文本模型: "${text}"`,
            geometry: {
                type: 'text3d',
                dimensions: {
                    text,
                    font: font || 'helvetiker',
                    height: height || 0.5,
                    depth: depth || 0.2
                }
            }
        };

        // 添加材质信息
        if (material) {
            modelData.geometry.material = material;
        }

        // 创建模型
        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '创建3D文本模型失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: '3D文本模型创建成功'
        });
    } catch (error) {
        console.error('创建3D文本模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建拉伸模型
 */
exports.createExtrudeModel = async (req, res) => {
    try {
        const {
            name,
            description,
            points,
            depth,
            bevelEnabled,
            bevelThickness,
            bevelSize,
            bevelSegments,
            material
        } = req.body;

        if (!name || !points || !Array.isArray(points) || points.length < 3) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：模型名称或至少3个点的轮廓点数组'
            });
        }

        // 创建模型数据
        const modelData = {
            name,
            description: description || `拉伸模型(${points.length}个轮廓点)`,
            geometry: {
                type: 'extrude',
                dimensions: {
                    points,
                    depth: depth || 1,
                    extrude: {
                        steps: 1,
                        depth: depth || 1,
                        bevelEnabled: bevelEnabled || false,
                        bevelThickness: bevelThickness || 0.2,
                        bevelSize: bevelSize || 0.1,
                        bevelSegments: bevelSegments || 3
                    }
                }
            }
        };

        // 添加材质信息
        if (material) {
            modelData.geometry.material = material;
        }

        // 创建模型
        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '创建拉伸模型失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: '拉伸模型创建成功'
        });
    } catch (error) {
        console.error('创建拉伸模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建车削模型
 */
exports.createLatheModel = async (req, res) => {
    try {
        const { name, description, points, segments, material } = req.body;

        if (!name || !points || !Array.isArray(points) || points.length < 2) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：模型名称或至少2个点的轮廓点数组'
            });
        }

        // 创建模型数据
        const modelData = {
            name,
            description: description || `车削模型(${points.length}个轮廓点)`,
            geometry: {
                type: 'lathe',
                dimensions: {
                    points,
                    segments: segments || 12
                }
            }
        };

        // 添加材质信息
        if (material) {
            modelData.geometry.material = material;
        }

        // 创建模型
        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '创建车削模型失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: '车削模型创建成功'
        });
    } catch (error) {
        console.error('创建车削模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建组合模型
 */
exports.createGroupModel = async (req, res) => {
    try {
        const { name, description, childModelIds, material } = req.body;

        if (!name || !childModelIds || !Array.isArray(childModelIds) || childModelIds.length === 0) {
            return res.status(400).json({
                status: 400,
                message: '缺少必要参数：模型名称或子模型ID数组'
            });
        }

        // 验证所有子模型是否存在且用户有权限访问
        const childModels = [];
        for (const childId of childModelIds) {
            const { success, data } = await modelService.getModelById(childId, req.userId);
            if (!success) {
                return res.status(400).json({
                    status: 400,
                    message: `子模型(ID: ${childId})不存在或无权限访问`
                });
            }
            childModels.push(data);
        }

        // 创建模型数据
        const modelData = {
            name,
            description: description || `组合模型(${childModels.length}个子模型)`,
            geometry: {
                type: 'group',
                children: childModelIds
            }
        };

        // 添加材质信息（如果提供，将应用到整个组）
        if (material) {
            modelData.geometry.material = material;
        }

        // 创建模型
        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error || '创建组合模型失败'
            });
        }

        return res.status(201).json({
            status: 201,
            data,
            message: '组合模型创建成功'
        });
    } catch (error) {
        console.error('创建组合模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 导出模型
 */
exports.exportModel = async (req, res) => {
    try {
        const { modelId, format } = req.params;
        const { quality } = req.query;

        // 验证导出格式
        if (!['stl', 'obj', 'gltf', 'glb'].includes(format)) {
            return res.status(400).json({
                status: 400,
                message: '不支持的导出格式，支持的格式有：stl, obj, gltf, glb'
            });
        }

        // 获取模型信息
        const { success, data: model, error } = await modelService.getModelById(modelId, req.userId);

        if (!success) {
            return res.status(404).json({
                status: 404,
                message: error || '模型不存在或无权限访问'
            });
        }

        // 确保存储目录存在
        const storagePath = await fileUtils.ensureStorageDir(req.userId, modelId);
        const exportFilePath = path.join(storagePath, `export_${Date.now()}.${format}`);

        // 导出设置
        const exportOptions = {
            quality: quality || (model.exportSettings ? model.exportSettings.quality : 'medium'),
            format
        };

        try {
            // 执行模型导出（这里需要实现具体的导出逻辑）
            const exportResult = await fileUtils.exportModel(model, exportFilePath, exportOptions);

            if (!exportResult.success) {
                return res.status(400).json({
                    status: 400,
                    message: exportResult.error || '模型导出失败'
                });
            }

            // 设置响应头，让浏览器下载文件
            res.setHeader('Content-Type', 'application/octet-stream');
            res.setHeader('Content-Disposition', `attachment; filename=${model.name}.${format}`);

            // 发送文件
            return res.sendFile(exportFilePath, (err) => {
                if (err) {
                    console.error('发送导出文件错误:', err);
                    return res.status(500).json({
                        status: 500,
                        message: '发送导出文件失败'
                    });
                }
                // 下载完成后清理临时文件
                fileUtils.deleteFile(exportFilePath).catch(err => {
                    console.error('删除临时导出文件错误:', err);
                });
            });
        } catch (exportError) {
            console.error('导出模型错误:', exportError);
            return res.status(500).json({
                status: 500,
                message: '导出模型失败: ' + exportError.message
            });
        }
    } catch (error) {
        console.error('导出模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 更新外部模型属性
 * 专门用于修改导入的外部模型的颜色、位置、大小等属性
 */
exports.updateExternalModel = async (req, res) => {
    try {
        const { modelId } = req.params;
        const {
            color,
            position,
            rotation,
            scale,
            material
        } = req.body;

        // 确保至少有一个字段需要更新
        if (!color && !position && !rotation && !scale && !material) {
            return res.status(400).json({
                status: 400,
                message: '请提供需要更新的属性'
            });
        }

        // 先获取当前模型信息
        const { success: getSuccess, data: currentModel } = await modelService.getModelById(modelId, req.userId);

        if (!getSuccess || !currentModel) {
            return res.status(404).json({
                status: 404,
                message: '找不到模型'
            });
        }

        // 确保是外部导入的模型
        if (!currentModel.geometry || currentModel.geometry.type !== 'external_model') {
            return res.status(400).json({
                status: 400,
                message: '只能更新外部导入模型的属性'
            });
        }

        // 准备更新数据
        const updateData = {
            geometry: { ...currentModel.geometry }
        };

        // 更新颜色
        if (color) {
            updateData.geometry.color = color;
        }

        // 更新位置
        if (position) {
            updateData.geometry.position = {
                ...updateData.geometry.position,
                ...position
            };
        }

        // 更新旋转
        if (rotation) {
            updateData.geometry.rotation = {
                ...updateData.geometry.rotation,
                ...rotation
            };
        }

        // 更新缩放
        if (scale) {
            updateData.geometry.scale = {
                ...updateData.geometry.scale,
                ...scale
            };
        }

        // 更新材质
        if (material) {
            updateData.geometry.material = {
                ...updateData.geometry.material,
                ...material
            };
        }

        // 执行更新
        const { success, message, error } = await modelService.updateModel(modelId, req.userId, updateData);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        // 重新生成缩略图
        try {
            // 确保存储目录存在
            const storagePath = await fileUtils.ensureStorageDir(req.userId, modelId);
            const thumbnailPath = path.join(storagePath, `geometry_thumbnail.png`);

            // 生成缩略图
            const base64Thumbnail = await fileUtils.generateGeometryThumbnail(updateData.geometry, thumbnailPath);

            // 更新模型缩略图信息
            await modelService.updateModel(modelId, req.userId, {
                thumbnail: {
                    path: thumbnailPath,
                    base64: base64Thumbnail,
                    generateDate: new Date()
                }
            });
        } catch (thumbnailError) {
            console.error('更新外部模型缩略图错误:', thumbnailError);
            // 缩略图更新失败不影响模型更新结果
        }

        return res.json({
            status: 200,
            message: '外部模型属性更新成功'
        });
    } catch (error) {
        console.error('更新外部模型属性错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
};

/**
 * 创建外部模型
 */
exports.createExternalModel = async (req, res) => {
    try {
        const {
            name,
            description,
            color,
            position,
            rotation,
            scale,
            material,
            exportSettings,
            sharing
        } = req.body;

        // 验证必填字段
        if (!name) {
            return res.status(400).json({
                status: 400,
                message: '模型名称不能为空'
            });
        }

        // 准备模型数据
        const modelData = {
            name,
            description,
            exportSettings,
            sharing,
            geometry: {
                type: 'external_model',
                color: color || '#FFFFFF',
                position: position || { x: 0, y: 0, z: 0 },
                rotation: rotation || { x: 0, y: 0, z: 0 },
                scale: scale || { x: 1, y: 1, z: 1 },
                material: material || {
                    type: 'standard',
                    wireframe: false,
                    metalness: 0.1,
                    roughness: 0.5,
                    opacity: 1.0,
                    transparent: false
                }
            }
        };

        const { success, data, error } = await modelService.createModel(modelData, req.userId);

        if (!success) {
            return res.status(400).json({
                status: 400,
                message: error
            });
        }

        // 为外部模型生成默认缩略图
        if (data.model && data.model.id) {
            try {
                // 确保存储目录存在
                const storagePath = await fileUtils.ensureStorageDir(req.userId, data.model.id);
                const thumbnailPath = path.join(storagePath, `external_model_thumbnail.png`);

                // 生成缩略图
                const base64Thumbnail = await fileUtils.generateGeometryThumbnail(modelData.geometry, thumbnailPath);

                // 更新模型缩略图信息
                await modelService.updateModel(data.model.id, req.userId, {
                    thumbnail: {
                        path: thumbnailPath,
                        base64: base64Thumbnail,
                        generateDate: new Date()
                    }
                });
            } catch (thumbnailError) {
                console.error('生成外部模型缩略图错误:', thumbnailError);
                // 缩略图生成失败不影响模型创建结果
            }
        }

        return res.status(201).json({
            status: 201,
            data: {
                ...data,
                message: '外部模型创建成功，请上传模型文件'
            }
        });
    } catch (error) {
        console.error('创建外部模型错误:', error);
        return res.status(500).json({
            status: 500,
            message: '服务器错误'
        });
    }
}; 